/*-------------------------------------------------------------------------------
* file:     app_factory.c
* brief:    application
* copyright Copyright (C) 2020-2022 @ NanoIC
* Date:     2023-09-06
* Version:  V1.00
* Author:   JMH
*-------------------------------------------------------------------------------*/

/* include ----------------------------------------------------------------*/
#include "app_factory.h"
#include "app_parameter.h"

/* externs function--------------------------------------------------------*/
extern unsigned int *chip_get_pin_name_addr(pin_name_e ePinName);

/* externs variablesr------------------------------------------------------*/
extern uint8_t one_wire_bus_app_sleep_or_wakeup_flag;

/* Private variablesr------------------------------------------------------*/
volatile bool global_factory_enter_on = false;
volatile uint8_t global_sn_lock;
static const uint8_t global_key_pin_test_one[FACTORY_ALL_IO_SHORT_TEST] = { PA012, PA013,PA014,PA015, PA10, PA12, PA13, PA14, PB011, PA00,// 
                                                                            PA15,  PB07, PB09, PA110, PA19, PC00, PB06, PB05, PA16};//

static const uint8_t global_key_pin_one[FACTORY_KEY_IO_ENGHT] = {PA012, PA013,PA014,PA015, PA10, PA12,  PA13, PA14, PB011, PA00};//
static const uint8_t global_key_pin_two[FACTORY_KEY_IO_ENGHT] = {PA15, 	PB07, PB09, PA110, PA19, PC00,  PB06, PB05, PA16,  PA16};//

volatile uint8_t sn_iQOO_or_V3pro;

 uint8_t factory_enter_flag = 0;
  uint8_t uk_flag = 0;
 void one_wire_bus_app_read_sn(uint8_t chose ,uint8_t * temp_buf);
/* Private function--------------------------------------------------------*/
/**
 * @brief 对单总线收到调试命令进行处理
 * 
 * @param p_rec_packet 收到数据包指针
 * 
 * @return true : 成功
 * @return false : 失败
 */
bool one_wrie_bus_app_rec_debug_cmd(SourcePacketStr *p_rec_packet)
{
    return true;
}

/**
 * @brief 产测初始化
 */
void app_factory_init(void)
{
	global_sn_lock = 0x01;
	one_wire_bus_app_read_sn(0x00,sn_val);
	if(sn_val[10]==1||sn_val[10]==5||sn_val[10]==6||sn_val[10]==7)
	{
		uk_flag=1;
	}
	uint8_t ret = one_wire_bus_app_read_acc(0x00,gsensor_cal);
//	printf("ret %d\n",ret);
	if(ret==0)
	{
		horizont_x = (short)(((unsigned short)gsensor_cal[1] << 8) + (unsigned short)gsensor_cal[0]);
		horizont_y = (short)(((unsigned short)gsensor_cal[3] << 8) + (unsigned short)gsensor_cal[2]);
		horizont_z = (short)(((unsigned short)gsensor_cal[5] << 8) + (unsigned short)gsensor_cal[4]);
//		printf("horizont: %d %d %d\n",horizont_x,horizont_y,horizont_z);
	}

}

/**
 * @brief 设置所有使用io输入，上下拉
 * 
 * @param mode 0 下拉  1上拉
 */
void app_set_all_io_input_pullup(uint8_t mode)
{
    for(uint16_t i = 0; i < FACTORY_ALL_IO_SHORT_TEST; i++)
    {
        app_io_input_pull_up(global_key_pin_test_one[i],mode);
    }
}

/**
 * @brief 设置所有使用io输出
 * 
 * @param mode 0 低电平  1高电平
 */
void app_set_all_io_output_mode(uint8_t mode)
{
    for(uint16_t i = 0; i < FACTORY_ALL_IO_SHORT_TEST; i++)
    {
        app_io_out_count(global_key_pin_test_one[i],mode);
    }
}

/**
 * @brief 筛选相连接的io
 * 
 * @param io_one 目标1
 * @param io_two 目标2
 * @return uint8_t 筛选结果
 */
uint8_t app_check_io(uint8_t io_one,uint8_t io_two)
{
	if((io_one == PA16)||(io_two == PA00) || (io_two == PB011))
    {
        if((io_two == PA00) || (io_two == PB011)||(io_one == PA16))
        {
            return 0;
        }
    } 
	 
    for(uint8_t k = 0; k < FACTORY_KEY_IO_ENGHT; k++)
    {
        if((global_key_pin_one[k] == io_one)&&(global_key_pin_two[k] == io_two))
        {
            return 0;
        }
        if((global_key_pin_two[k] == io_one)&&(global_key_pin_one[k] == io_two))
        {
            return 0;
        }
    }


    return 1;
}

/**
 * @brief 测试io开路
 * 
 * @param pin_num 选择通道
 * @return uint32_t 返回信息
 */
uint32_t app_keyboard_io_open_test(void)
{
     uint32_t *ptPinInfo;
    uint8_t err_falg = 0;
    uint8_t gpio_num = 0;
    uint8_t i=0,j=0;
    for(i = 0; i < FACTORY_KEY_IO_ENGHT; i++)
    {
        app_io_input_pull_up(global_key_pin_one[i],0x01);
		udelay(10);
        app_io_out_count(global_key_pin_two[i],0x00);
		udelay(10);
    }
    udelay(50);
    for(j = 0; j < FACTORY_KEY_IO_ENGHT; j++)
    {
        if(csi_pin_read(global_key_pin_one[j]) == 0x01)
        {
            ptPinInfo = chip_get_pin_name_addr(global_key_pin_one[j]);
            err_falg  = ptPinInfo[1];//ePinName
            gpio_num  = ptPinInfo[2];//gpio
            #if FACTORY_MODE_ON
                printf("3 - %d\n",j);
                printf("%x %x \n",gpio_num,err_falg);
            #endif
			return (((gpio_num&0x000000ff)<<8)|err_falg&0x000000ff);
        } 
    }
    udelay(50);
    for(i = 0; i < FACTORY_KEY_IO_ENGHT; i++)
    {
        app_io_input_pull_up(global_key_pin_two[i],0x01);
		udelay(10);
        app_io_out_count(global_key_pin_one[i],0x00);
		udelay(10);
    }
    udelay(50);
    for(j = 0; j < FACTORY_KEY_IO_ENGHT; j++)
    {
        if(csi_pin_read(global_key_pin_two[j]) != 0x00)
        {
            ptPinInfo = chip_get_pin_name_addr(global_key_pin_two[j]);
            err_falg  = ptPinInfo[1];
            gpio_num  =	ptPinInfo[2];
            #if FACTORY_MODE_ON
                printf("4 - %d\n",j);
                printf("%x %x \n",gpio_num,err_falg);
            #endif
            //return (((uint16_t)gpio_num<<8) | err_falg);
			return (((gpio_num&0x000000ff)<<8)|err_falg&0x000000ff);
        } 
    }
    return (((uint16_t)gpio_num<<8) | err_falg);
}

/**
 * @brief 测试io短路
 * @return uint32_t 返回信息
 */
uint32_t app_keyboard_io_short_circuit_test(void)
{
     uint32_t err_falg = 0;
    uint32_t gpio_num = 0;
    uint32_t *ptPinInfo;
    uint16_t i,j;

    app_set_all_io_input_pullup(0x01);
    udelay(50);
    for(i = 0; i < FACTORY_ALL_IO_SHORT_TEST; i++)
    {
        //输出0
        app_io_out_count(global_key_pin_test_one[i],0x00);
        udelay(50); 
        for(j = 0; j < FACTORY_ALL_IO_SHORT_TEST; j++)
        {
            if(i == j)
            {
                continue;
            }
            if(csi_pin_read(global_key_pin_test_one[j]) == 0x00)
            {
                uint8_t check_io_pin = app_check_io((uint8_t)global_key_pin_test_one[i],(uint8_t)global_key_pin_test_one[j]);
                if(check_io_pin == 0)
                {
                    continue;
                }
                ptPinInfo = chip_get_pin_name_addr(global_key_pin_test_one[j]);
                err_falg  = ptPinInfo[1];//ePinName
                gpio_num  = ptPinInfo[2];//gpio
                #if FACTORY_MODE_ON
                    printf("11 - %d %d \n",i,j);
                    printf("%x %x \n",gpio_num,err_falg);
                #endif
                //return (((uint16_t)gpio_num<<8) | err_falg);
				return (((gpio_num&0x000000ff)<<8)|err_falg&0x000000ff);
				//return (global_key_pin_test_one[j]);
            }  
        }
        app_io_input_pull_up(global_key_pin_test_one[i],0x01);
        udelay(50);
    }

    //设置所有io输出低电平
    app_set_all_io_output_mode(0x00);
    udelay(50);
    for(i = 0; i < FACTORY_KEY_IO_ENGHT; i++)
    {
        //设置上拉，判断是否被拉低，拉低则短路
        app_io_input_pull_up(global_key_pin_one[i],0x01);
        app_io_input_pull_up(global_key_pin_two[i],0x01);
        udelay(50); 
		if(global_key_pin_two[i] == PA16)
        {
            app_io_input_pull_up(PB011,0x01);
            app_io_input_pull_up(PA00,0x01);
            udelay(50);
        } 
        if((csi_pin_read(global_key_pin_two[i])) && (csi_pin_read(global_key_pin_one[i])))
        {
            app_set_all_io_output_mode(0x00);
            udelay(50);
            continue;
        }
        ptPinInfo = chip_get_pin_name_addr(global_key_pin_one[i]);
        err_falg  = ptPinInfo[1];
        gpio_num  = ptPinInfo[2];
        #if FACTORY_MODE_ON
            printf("2 - %d %d \n",i,j);
            printf("%x %x \n",gpio_num,err_falg);
        #endif
        //return (((uint16_t)gpio_num<<8) | err_falg);
		//return (((uint16_t)err_falg<<8)|gpio_num );
		//return (((err_falg&0x000000ff)<<8)|gpio_num&0x000000ff);
		return (((gpio_num&0x000000ff)<<8)|err_falg&0x000000ff);
    }
	 
    return 0;
}

/**
 * @brief led io测试
 * 
 * @return uint32_t 
 */
uint32_t app_kebord_io_led_test(void)
{
    uint8_t err_falg = 0;
    uint8_t gpio_num = 0;
    uint32_t *ptPinInfo;

    //将两个io拉高电平，读取对应io为低电平，则通过，反之如此
    app_io_out_count(Caps_LED_PIN,0x01);
    app_io_out_count(MIC_LED_PIN,0x00);
    udelay(50);
    app_io_input_pull_up(PB02,1);

    if(csi_pin_read(PB02))
    {
        ptPinInfo = chip_get_pin_name_addr(Caps_LED_PIN);
        err_falg  = *ptPinInfo>>8;
        gpio_num  = *ptPinInfo>>16;
        return (((uint16_t)gpio_num<<8) | err_falg);
    }
    app_io_out_count(Caps_LED_PIN,0x00);
    app_io_out_count(MIC_LED_PIN,0x01);
    udelay(50);
    if(csi_pin_read(PB02))
    {
        ptPinInfo = chip_get_pin_name_addr(MIC_LED_PIN);
        err_falg  = *ptPinInfo>>8;
        gpio_num  = *ptPinInfo>>16;
    }
    return (((uint16_t)gpio_num<<8) | err_falg);
}

/**
 * @brief 测试项目选择执行
 * 
 * @param p_buf 输入数据指针
 * @param data_len 数据长度
 */
bool app_factory_test_star(uint8_t * p_buf ,uint8_t data_len)
{
    if(p_buf[0] != FACTOR_TEST_FLAG_CMD)
        return false;
    global_factory_enter_on = true;
    app_enter_factor_mode(true);
    #if FACTORY_MODE_ON
    printf("enter factory mode\n");
    #endif
    uint8_t factory_ack_buf[10] = {0};
    factory_ack_buf[2] = FACTOR_TEST_FLAG_CMD;
    uint32_t key_test_result = 0;

    if(p_buf[2] == 0x01) //键盘io测试
    {
        key_test_result = app_keyboard_io_short_circuit_test();
        if(!key_test_result)
        {
            key_test_result = app_keyboard_io_open_test();
        }
        factory_ack_buf[0] = 0x07;
        factory_ack_buf[1] = 0x03;
        factory_ack_buf[3] = 0x00;
        factory_ack_buf[4] = (key_test_result>>8)&0xFF;
        factory_ack_buf[5] = key_test_result & 0xFF;
        // one_wire_bus_tra_write_long_frame_to_queue(factory_ack_buf,6,ONE_WIRE_BUS_CMD_FACTORY_DEV_ACK,0,true);
        one_wire_bus_app_manufactory_ack(factory_ack_buf,6);
        if(key_test_result)
        {
            app_enter_factor_mode(false);
            global_factory_enter_on = false;
            return false;
        }
    }
//    if(p_buf[3] == 0x01) //触摸板io测试
//    {
//        factory_ack_buf[0] = 0x08;
//        factory_ack_buf[1] = 0x03;
//        factory_ack_buf[3] = 0x00;
//        factory_ack_buf[4] = (key_test_result>>8)&0xFF;
//        factory_ack_buf[5] = key_test_result & 0xFF;
//        one_wire_bus_app_manufactory_ack(factory_ack_buf,6);
//    }
//    if(p_buf[4] == 0x01) //HAll io 测试
//    {
//        uint32_t hall_status_buf;
//        hall_status_buf = csi_pin_read(HALL_BUTTON_PIN);
//        factory_ack_buf[0] = 0x09;
//        factory_ack_buf[1] = 0x03;
//        factory_ack_buf[3] = 0x00;
//        factory_ack_buf[4] = hall_status_buf == 0x00 ? 0x00 : 0x01;
//        factory_ack_buf[5] = 0x00;
//        one_wire_bus_app_manufactory_ack(factory_ack_buf,6);
//    }
    if(p_buf[5] == 0x01) //LED io测试
    {
//        key_test_result = app_kebord_io_led_test();
        factory_ack_buf[0] = 0x0a;
        factory_ack_buf[1] = 0x03;
        factory_ack_buf[3] = 0x00;
        factory_ack_buf[4] = (key_test_result>>8)&0xFF;
        factory_ack_buf[5] = key_test_result & 0xFF;
        one_wire_bus_app_manufactory_ack(factory_ack_buf,6);
        if(key_test_result)
        {
            return false;
        }
    }
    if(p_buf[6] == 0x01) //G_sensor io 测试
    {
    }
    factory_ack_buf[0] = 0x0C;
    factory_ack_buf[1] = 0x01;
    factory_ack_buf[3] = 0x02;
    one_wire_bus_app_manufactory_ack(factory_ack_buf,4);
    return true;
}

//---------------------------------------------------------------------------------
/**
 * @brief 解锁sn
 * 
 * @param p_buf 
 */
void one_wire_bus_app_sn_unlock(uint8_t * p_buf)
{
    uint8_t read_sn1[40] = {0};
    uint8_t read_sn2[40] = {0};

    app_iwt_clr();
    app_spi_flash_page_read(FLASH_FCT_ADDR,(uint8_t *)&read_sn1[0],33);
    app_iwt_clr();
    app_spi_flash_page_read(FLASH_FCT_ADDR1,(uint8_t *)&read_sn2[0],33);
    app_iwt_clr();

    if(p_buf[0]== 0x0B)
    {
        read_sn1[1] = 0x00;
        read_sn2[1] = 0x00;
        drv_flash_lock_config(UNLOCK);
        boot_flash_unlock_flash(UNLOCK);
        app_iwt_clr();
        app_spi_flash_sector_or_block_erase(FLASH_FCT_ADDR,FLASH_SECTOR_SIZE);
        app_iwt_clr();
        app_spi_flash_sector_or_block_erase(FLASH_FCT_ADDR1,FLASH_SECTOR_SIZE);
        app_iwt_clr();
        app_spi_flash_page_program(FLASH_FCT_ADDR,(uint8_t *)&read_sn1[0],40);
        app_iwt_clr();
        app_spi_flash_page_program(FLASH_FCT_ADDR1,(uint8_t *)&read_sn2[0],40);
        app_iwt_clr();
        drv_flash_lock_config(AREA_00000_2FFFF);
        boot_flash_lock_flash(AREA_00000_2FFFF);
        app_iwt_clr();
        global_sn_lock = 0x00;
    }else
    {
        global_sn_lock = 0x01;
    }
}

/**
 * @brief 查看sn锁状态
 * 
 * @return uint8_t 返回状态
 */
uint8_t one_wire_bus_app_sn_check_lock(void)
{
    uint8_t read_sn1[33] = {0};
    uint8_t read_sn2[33] = {0};

    app_iwt_clr();
    app_spi_flash_page_read(FLASH_FCT_ADDR,(uint8_t *)&read_sn1[0],33);
    app_iwt_clr();
    app_spi_flash_page_read(FLASH_FCT_ADDR1,(uint8_t *)&read_sn2[0],33);
    app_iwt_clr();

    //出厂
    if((read_sn1[0] == read_sn2[0]) && (read_sn1[0] == 0xFF))
        return 0;
    if((read_sn1[1] == 0x01) && (read_sn2[1] == 0x01))
    {
        //上锁状态
        global_sn_lock = 0x01;
    }else if((read_sn1[1] == 0x00) && (read_sn2[1] == 0x00))
    {
        //解锁状态
        global_sn_lock = 0x00;
    }
    return 2;
}

/**
 * @brief 读取SN号 
 * byte 0 长度
 * byte 1 crc
 * byte 2 - 32 SN
 */
void one_wire_bus_app_read_sn(uint8_t chose ,uint8_t * temp_buf)
{
    uint8_t read_sn1[33] = {0};
//    uint8_t read_sn2[33] = {0};
    uint8_t read_flsh_reply[38] = {0};
    uint8_t read_data_len = 0;
    uint8_t status = 0;
    app_iwt_clr();
    app_spi_flash_page_read(FLASH_FCT_ADDR,(uint8_t *)&read_sn1[0],33);
    app_iwt_clr();


    read_data_len = read_sn1[0];
    if(read_data_len > 16)
        status = 1;
    else if(read_sn1[2] != one_wire_bus_get_buf_sum((uint8_t*)&read_sn1[3],read_data_len))
         status = 2;
		 
		 
	for(uint8_t i=0;i<16;i++)
	{
		 if (read_sn1[i+3] >= '0' && read_sn1[i+3] <= '9')
		{
		}
		else if (read_sn1[i+3] >= 'A' && read_sn1[i+3] <= 'Z')
		{
		}
		else
		{
			 #if FACTORY_MODE_ON
			printf("SN error!\n");
			#endif
			status = 3;
			break;
		}
	}
	if( !status)
	{
		
		for(uint8_t i = 0; i < read_data_len; i++)
		{
			read_flsh_reply[i+5] = read_sn1[i+3];
			if(temp_buf != NULL )
			{
				temp_buf[i] = read_sn1[i+3];
			}
		}
	}

	
    read_flsh_reply[0] = 0x14;
    read_flsh_reply[1] = 0x05;
    read_flsh_reply[2] = 0x02;
    read_flsh_reply[3] = 0x04;
	read_flsh_reply[4] = status;
    if(chose == 1)
    {
        one_wire_bus_app_manufactory_ack(read_flsh_reply,read_data_len+5);
    }else if(chose == 0)
    {
	
        return;
    }
}

/**
 * @brief 写入SN号
 * 
 * @param p_buf 数据指针
 * @param data_len 数据长度
 */
void one_wire_bus_app_write_sn(uint8_t * p_buf,uint8_t data_len)
{
    uint8_t write_sn[256] = {0};
    uint8_t return_sn_status[5] = {0};
    uint16_t write_status1,write_status2;
    uint8_t status = 1;
	if(data_len!=16)
	{
		status=2;
	}else{

//		if((lock_status == 0x00) || (global_sn_lock == 0x00))
		{
			write_sn[0] = data_len;
			write_sn[1] = 0x01;//上锁
			write_sn[2] = one_wire_bus_get_buf_sum((uint8_t*)&p_buf[0],data_len);
			for(uint8_t i = 0; i < data_len; i++)
			{
				write_sn[i+3] = p_buf[i];
			}
			app_iwt_clr();
			drv_flash_lock_config(UNLOCK);
			boot_flash_unlock_flash(UNLOCK);
			app_iwt_clr();
			app_spi_flash_sector_or_block_erase(FLASH_FCT_ADDR,FLASH_SECTOR_SIZE);
			app_iwt_clr();
//			app_spi_flash_sector_or_block_erase(FLASH_FCT_ADDR1,FLASH_SECTOR_SIZE);
//			app_iwt_clr();
			write_status1 = app_spi_flash_page_program(FLASH_FCT_ADDR,(uint8_t *)&write_sn[0],FLASH_PAGE_SIZE);
			app_iwt_clr();
//			write_status2 = app_spi_flash_page_program(FLASH_FCT_ADDR1,(uint8_t *)&write_sn[0],FLASH_PAGE_SIZE);
//			app_iwt_clr();
			drv_flash_lock_config(AREA_00000_2FFFF);
			boot_flash_lock_flash(AREA_00000_2FFFF);
			app_iwt_clr();
			global_sn_lock = 0x01;
			if(write_status1 /*&& write_status2*/)
			{
				status = 0x00;
			}
		}
	}

    return_sn_status[0] = 0x14;
    return_sn_status[1] = 0x05;
    return_sn_status[2] = 0x02;
    return_sn_status[3] = 0x03;
    return_sn_status[4] = status;
    one_wire_bus_app_manufactory_ack(return_sn_status,5);
}

/**
 * @brief 读取g-sensor校准数据
 * byte 0 长度  
 * byte 1 crc
 * byte 2 - 32 SN
 */
uint8_t one_wire_bus_app_read_acc(uint8_t chose ,uint8_t * temp_buf)
{
    uint8_t read_sn1[33] = {0};
    uint8_t read_data_len = 0;
    uint8_t status = 0;
    app_iwt_clr();
    app_spi_flash_page_read(FLASH_FCT_ADDR1,(uint8_t *)&read_sn1[0],33);
    app_iwt_clr();


    read_data_len = read_sn1[0];
    if(read_data_len != 6)
        status = 1;
    else if(read_sn1[2] != one_wire_bus_get_buf_sum((uint8_t*)&read_sn1[3],read_data_len))
         status = 2;
	if( !status)
	{
		
		for(uint8_t i = 0; i < read_data_len; i++)
		{
			if(temp_buf != NULL )
			{
				temp_buf[i] = read_sn1[i+3];
			}
		}
	}
	return status;
    
}

/**
 * @brief 写入g-sensor校准数据
 * 
 * @param p_buf 数据指针
 * @param data_len 数据长度
 */
uint8_t one_wire_bus_app_write_acc(uint8_t * p_buf,uint8_t data_len)
{
    uint8_t write_sn[256] = {0};
    uint16_t write_status1,write_status2;
    uint8_t status = 1;
	if(data_len!=6)
	{
		status=2;
	}else{

//		if((lock_status == 0x00) || (global_sn_lock == 0x00))
		{
			write_sn[0] = data_len;
			write_sn[1] = 0x01;//上锁
			write_sn[2] = one_wire_bus_get_buf_sum((uint8_t*)&p_buf[0],data_len);
			for(uint8_t i = 0; i < data_len; i++)
			{
				write_sn[i+3] = p_buf[i];
			}
			app_iwt_clr();
			drv_flash_lock_config(UNLOCK);
			boot_flash_unlock_flash(UNLOCK);
			app_iwt_clr();
			app_spi_flash_sector_or_block_erase(FLASH_FCT_ADDR1,FLASH_SECTOR_SIZE);
			app_iwt_clr();

			write_status1 = app_spi_flash_page_program(FLASH_FCT_ADDR1,(uint8_t *)&write_sn[0],FLASH_PAGE_SIZE);
			app_iwt_clr();

			drv_flash_lock_config(AREA_00000_2FFFF);
			boot_flash_lock_flash(AREA_00000_2FFFF);
			app_iwt_clr();
			global_sn_lock = 0x01;
			if(write_status1 /*&& write_status2*/)
			{
				status = 0x00;
			}
		}
	}
	return status;
}


//---------------------------------------------------------------------------------
uint32_t rcv_0x80_cnt = 0,send_80_cnt = 0;

/**
 * @brief 处理丢包测试数据
 * 
 * @param pdata 
 */
void deal_with_0x80_cmd(uint8_t *pdata)
{
    if (pdata[2] == 0xF2){
        rcv_0x80_cnt ++;
        if (one_wire_bus_app_manufactory_ack(pdata,pdata[1] + 3)){
            send_80_cnt ++;
        }
    }
}




void app_factory_test_sleep_cmd_set(void)
{
	if(ota_first_flag)
	{
		return;
	}
    app_lowpower_sleep_set();
    one_wire_bus_app_sleep_or_wakeup_flag = 1;
}
void one_wire_bus_app_read_fw_ver()
{
	uint8_t buf[15]={0};
	buf[0] = 0x14;
    buf[1] = 0x01;
    buf[2] = 0x01;
    buf[3] = 0x01;
	buf[4] = 0x00;
	memcpy(&buf[5],factory_version_vel,sizeof(factory_version_vel));
    one_wire_bus_app_manufactory_ack(buf,5+sizeof(factory_version_vel));
}
void one_wire_bus_app_read_hw_ver()
{
	uint8_t buf[10]={0};
	buf[0] = 0x14;
    buf[1] = 0x01;
    buf[2] = 0x01;
    buf[3] = 0x02;
    buf[4] = 0x00;
	memcpy(&buf[5],device_version,sizeof(device_version));
	 one_wire_bus_app_manufactory_ack(buf,5+sizeof(device_version));
}
void device_test_pro(uint8_t *data,uint16_t len)
{
	
    switch(data[0])
    {
	
		case 0x01:      //版本号 
			if(data[1]==0x01)
			{
				one_wire_bus_app_read_fw_ver();
			}else if(data[1]==0x02)
			{
				one_wire_bus_app_read_hw_ver();
			}
		break;
       
		case 0x03:       			// 开关机
				;
		break;

		case 0x05:  					//功耗测试，进入待机
//			app_factory_test_sleep_cmd_set();						
		break;

		default:break;
	}
}
void peripherals_test_pro(uint8_t *data,uint16_t len)
{
	uint8_t factory_buf[10];
	    switch(data[0])
    {
	
		case 0x01:      //RTC  
		
		break;

		case 0x04:  					//TP
			if(data[1]==0x01)
			{
				factory_buf[0] = 0x14;
				factory_buf[1] = 0x02;
				factory_buf[2] = 0x04;
				factory_buf[3] = 0x01;
				factory_buf[4] = 0x00;
				memcpy(&factory_buf[5], (uint8_t*)&TP_ID, 4);
					one_wire_bus_app_manufactory_ack(factory_buf,9);
			}else if(data[1]==0x02){
				factory_buf[0] = 0x14;
				factory_buf[1] = 0x02;
				factory_buf[2] = 0x04;
				factory_buf[3] = 0x02;
				factory_buf[4] = 0x00;
				factory_buf[5] = TP_version;
				one_wire_bus_app_manufactory_ack(factory_buf,6);
			}		
		break;
		case 0x10:  					//LED
									
		break;

		default:break;
	}
}

//获取系数
void sensor_horizontal_calibration(uint8_t *data)
{
//	coefficient_x = (data[2] << 8) | data[3]; 
//	coefficient_y = (data[4] << 8) | data[5];
//	coefficient_z = (data[6] << 8) | data[7];

	coefficient_x = (short)(((unsigned short)data[1] << 8) + (unsigned short)data[0]);
	coefficient_y = (short)(((unsigned short)data[3] << 8) + (unsigned short)data[2]);
	coefficient_z = (short)(((unsigned short)data[5] << 8) + (unsigned short)data[4]);
}

//获取系数
void sensor_cal_offset(uint8_t *data)
{
	cal_offset = (unsigned short)(((unsigned short)data[1] << 8) + (unsigned short)data[0]);
}

void sensor_test_pro(uint8_t *data,uint16_t len)
{
	uint8_t gsentor_data[11]={0};
	uint8_t gsensor_factory_test_data[6] = {0};
	uint8_t ret=1;
	if(data[0]==1)
	switch(data[1])
    {
	
		case 0x01:      		//读取ACC原始值  

			gsensor_raw_value_flag=1;
		break;

		case 0x02:  			//ACC水平校准
			gsensor_level_cal_flag=1;	
			sensor_horizontal_calibration(data+2);		
		break;
		case 0x03:  			//读取ACC校准后的值
			gsensor_cal_value_flag=1;						
		break;
		
		case 0x04:  			//读取ACC校准系数
		
			gsensor_cal_cfg_flag=1;			
		break;
		case 0x05:  			//ACC自检指令
			gsensor_cal_offset_flag=1;			
			sensor_cal_offset(data+2);						
		break;
		case 0x07:  			//ACC开始数据上报
			gsensor_data_up_flag=1;								
		break;
		
		case 0x08:  			//ACC读取ID
						
		break;
		case 0x0A:  			//ACC停止数据上报
			gsensor_data_up_flag=0;						
		break;
		case 0x0B:  			//清除校准数据
			gsensor_clear_cal_data_flag=1;						
		break;
		
		default:break;
	}
}
void function_test_pro(uint8_t *data,uint16_t len)
{
		uint8_t buf[5]={0};
	if(data[0]==2)
	switch(data[1])
    {
	
		case 0x01:      //进入MMI1测试（半成品）  
			factory_enter_flag=1;
			
			buf[0] = 0x14;
			buf[1] = 0x04;
			buf[2] = 0x02;
			buf[3] = factory_enter_flag;
			buf[4] = 0x00;
			 one_wire_bus_app_manufactory_ack(buf,5);
		break;

		case 0x02:  					//进入MMI2测试（成品）
			factory_enter_flag=2;		
			buf[0] = 0x14;
			buf[1] = 0x04;
			buf[2] = 0x02;
			buf[3] = factory_enter_flag;
			buf[4] = 0x00;
			 one_wire_bus_app_manufactory_ack(buf,5);	
		break;
	
		default:break;
	}
}

void Custom_Information(uint8_t *data,uint16_t len)
{
	switch(data[0])
    {
	
		case 0x03:      //写SN 
			one_wire_bus_app_write_sn(&data[1],len-1);
			factory_enter_flag=1;
		break;

		case 0x04:  					//读取SN
			one_wire_bus_app_read_sn(factory_enter_flag,NULL);		
		break;
		
		
	
		default:break;
	}
}
void information_test_pro(uint8_t *data,uint16_t len)
{
	switch(data[0])
    {
	
		case 0x01:      //蓝牙信息 
		
		break;

		case 0x02:  					//定制信息
			Custom_Information(&data[1],len-1);			
		break;
		
		
		case 0x03:  					//端口加解锁
						
		break;
	
		default:break;
	}
	
}

void gpio_test_pro(uint8_t *data,uint16_t len)
{
	uint8_t test_gpio_ret_dat[9]={0};
	uint32_t ret=1;
	test_gpio_ret_dat[0] = 0x14;
	test_gpio_ret_dat[1] = 0x07;
	test_gpio_ret_dat[2] = 0x01;
	if(data[0]==0x01)
	{
		switch(data[1])
		{
	 
			case 0x01:      //开路测试 
				ret=app_keyboard_io_open_test();
				test_gpio_ret_dat[3] = 0x01;
				
			break;

			case 0x02:  					//短路测试
				ret=app_keyboard_io_short_circuit_test();	
//				printf("ret=%u\n",ret);
				test_gpio_ret_dat[3] = 0x02;
				
			break;
			
			case 0x03:  					//led io测试
				ret=app_kebord_io_led_test();			
				test_gpio_ret_dat[3] = 0x03;
			break;
	 
			default:break;
		}

		if(ret==0)
		{
			test_gpio_ret_dat[4] = 0x00;
		}
		else
		{
			test_gpio_ret_dat[4] = 0x01;
			test_gpio_ret_dat[5] =ret&0xff;
			test_gpio_ret_dat[6] =  ret>>8;
			//memcpy(&test_gpio_ret_dat[5],&ret,4);
		}
		one_wire_bus_app_manufactory_ack(test_gpio_ret_dat,9);
		for(int i=0;i<9;i++)
		{
			 #if FACTORY_MODE_ON
			printf("test_gpio_ret_dat[%d]=%d\n",i,test_gpio_ret_dat[i]);
			#endif
		}
		
	}
	
}
//---------------------------------------------------------------------------------
/**
 * @brief 对单总线收到工厂命令进行处理
 * 
 * @param p_rec_packet 收到数据包指针
 * 
 * @return true : 成功
 * @return false : 失败
 */
bool one_wrie_bus_app_rec_factory_cmd(SourcePacketStr *p_rec_packet,uint16_t len)
{
    #if FACTORY_MODE_ON
        printf("recdata  =  \n");
        console_log_num_byte(&p_rec_packet->data[0],p_rec_packet->len);
    #endif

    switch(p_rec_packet->cid)
    {
	
		case 0x01:      //设备管理  
				device_test_pro(p_rec_packet->data,len-2);
		break;
		case 0x02: 			//外设管理	
			peripherals_test_pro(p_rec_packet->data,len-2);
		break;        
		case 0x03:       			// sensor管理
				sensor_test_pro(p_rec_packet->data,len-2);
		break;
		case 0x04:  					//功能测试
				function_test_pro(p_rec_packet->data,len-2);					
		break;
		case 0x05:  					//信息管理
				information_test_pro(p_rec_packet->data,len-2);					
		break;
		case 0x07:  					//pcba测试
			
			gpio_test_pro(p_rec_packet->data,len-2);					
		break;

		default:break;
	

    }
    return true;
}

//-----------------------------------------------------------------------------
/**
 * @brief   设置为输入,上拉或下拉
 * 
 * @param   引脚
 * @return  上下拉选项
 */
void app_io_input_pull_up(uint8_t pin,uint8_t pull)
{
    csp_gpio_t *ptGpioBase;
    uint8_t index;
    uint32_t *ptPinInfo;

    ptPinInfo  = chip_get_pin_name_addr(pin);
    ptGpioBase = (csp_gpio_t *)ptPinInfo[0];   //pin addr
    index      = (pin_name_e)ptPinInfo[1];     //pin
    //--------------------------------------------
    // set pin input
    if(index < 8)
    {
        ptGpioBase->CONLR = (ptGpioBase->CONLR & ~(0xF << 4*index)) | (GPIO_DIR_INPUT << 4*index);
    }
    else
    {
        ptGpioBase->CONHR = (ptGpioBase->CONHR & ~(0xF << 4*(index-8))) | (GPIO_DIR_INPUT << 4*(index-8));
    }
    //--------------------------------------------
    // set pull up
    if(pull)
    {
        ptGpioBase->PUDR = ((ptGpioBase->PUDR) & ~(0x03 << (index*2))) | (0x01 << (index*2));
    }else
    {
        ptGpioBase->PUDR = ((ptGpioBase->PUDR) & ~(0x03 << (index*2))) | (0x02 << (index*2));
        // ptGpioBase->PUDR  = ((ptGpioBase->PUDR) & ~(0x03 << (index*2)));
    }
}

/**
 * @brief   设置为高阻态,上拉或下拉
 * 
 * @param   引脚
 * @return  上下拉选项
 */
void app_io_gpd_pull_up(uint8_t pin,uint8_t pull)
{
    csp_gpio_t *ptGpioBase;
    uint8_t index;
    uint32_t *ptPinInfo;

    ptPinInfo  = chip_get_pin_name_addr(pin);
    ptGpioBase = (csp_gpio_t *)ptPinInfo[0];   //pin addr
    index      = (pin_name_e)ptPinInfo[1];     //pin
    //--------------------------------------------
    // set pin input
    if(index < 8)
    {
        ptGpioBase->CONLR = (ptGpioBase->CONLR & ~(0xF << 4*index)) | (GPIO_DIR_GPD << 4*index);
    }
    else
    {
        ptGpioBase->CONHR = (ptGpioBase->CONHR & ~(0xF << 4*(index-8))) | (GPIO_DIR_GPD << 4*(index-8));
    }
    //--------------------------------------------
    // set pull up
    if(pull)
    {
        ptGpioBase->PUDR = ((ptGpioBase->PUDR) & ~(0x03 << (index*2))) | (0x01 << (index*2));
    }else
    {
        ptGpioBase->PUDR = ((ptGpioBase->PUDR) & ~(0x03 << (index*2))) | (0x02 << (index*2));
        // ptGpioBase->PUDR  = ((ptGpioBase->PUDR) & ~(0x03 << (index*2)));
    }
}

/**
 * @brief ：输出高或低电平，禁用上下拉
 * 
 * @param pin:引脚
 * @return
 */
void app_io_out_count(uint8_t pin,uint8_t status)
{
    csp_gpio_t *ptGpioBase = NULL;
    uint8_t index;
    uint32_t *ptPinInfo;

    ptPinInfo  = chip_get_pin_name_addr(pin);
    ptGpioBase = (csp_gpio_t *)ptPinInfo[0];   //pin addr
    index      = (pin_name_e)ptPinInfo[1];     //pin
    //--------------------------------------------
    // set pin output
    if(index < 8)
    {
        ptGpioBase->CONLR = (ptGpioBase->CONLR & ~(0xF << 4*index)) | (GPIO_DIR_OUTPUT << 4*index);
    }
    else
    {
        ptGpioBase->CONHR = (ptGpioBase->CONHR & ~(0xF << 4*(index-8))) | (GPIO_DIR_OUTPUT << 4*(index-8));
    }
    if(status)
    {
        ptGpioBase->WODR = ptGpioBase->ODSR | (0x1 << index);
    }else
    {
        ptGpioBase->WODR = ptGpioBase->ODSR & (~(0x1 << index));
    }
	ptGpioBase->PUDR = ((ptGpioBase->PUDR) & ~(0x03 << (index*2)));
}


uint16_t control_rx_packet_tick=0;

void app_factory_0_1ms_callback(void)
{
	control_rx_packet_tick++;
	
}

uint8_t button_press_flag=0;
uint8_t key_press_flag=0;
uint16_t send_num=100;
uint8_t start_send_pack_test_flag=0;
uint16_t receive_pack_num=0;

 void send_test_packet(void)
{
	if(send_num>0)
	{
		uint8_t data[] = {0x3A,0xFF,0x01,0x01,0x02};
		one_wire_bus_app_send_long_keyboard_custom_data(0x80,data,5);//键盘发送，不需要ACK
		send_num--;
	}
	if(send_num==0)
	{
		uint8_t data[] = {0x3A,0xFF,0x01,0x01,0x10};
		one_wire_bus_app_send_long_keyboard_custom_data(0x90,data,5);//键盘发送，需要ACK
		start_send_pack_test_flag = 0;
		rec_single_evt_test(MaintenanceServiceID,REMOTE_UART_SEND_TEST,0x01,0x01,0x02);
		rec_single_evt_test(MaintenanceServiceID,REMOTE_UART_SEND_TEST_NUM,0x01,0x01,receive_pack_num&0xff);
		rec_single_evt_test(MaintenanceServiceID,REMOTE_UART_SEND_TEST_NUM,0x01,0x01,(receive_pack_num>>8)&0xff);
	}
}

void app_key_control_TR_packet_test(void)
{
	if(one_wire_bus_app_sleep_or_wakeup_flag||ota_first_flag||!pad_lcd_state)
	{
		control_rx_packet_tick=0;
		return;
	}
	if(button_press_flag==1 && start_send_pack_test_flag==0)//按键按下，亮屏&&pad_lcd_state==1
	{
		uint8_t data[] = {0x3A,0xFF,0x01,0x01,0x01};
		one_wire_bus_app_send_long_keyboard_custom_data(0x90,data,5);//键盘发送，需要ACK
		button_press_flag=0;
		start_send_pack_test_flag=1;	
		control_rx_packet_tick = 0;
//		send_num=UART_SEND_STES_SUM;//设置发送次数
		receive_pack_num=0;
		rec_single_evt_test(MaintenanceServiceID,REMOTE_UART_SEND_TEST,0x01,0x01,0x01);
	}
	if(start_send_pack_test_flag==2)
	{
		if(control_rx_packet_tick>=KEY_send_packet_TIMER_N)
		{
			control_rx_packet_tick=0;
			send_test_packet();
		}
	}

}


